import axios from 'axios'
import { Message } from 'element-ui'
import router from '@/router'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 从localStorage获取token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = 'Bearer ' + token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 403:
          Message({
            message: '登录已过期，请重新登录',
            type: 'error',
            duration: 2000
          })
          // 清除token
          localStorage.clear()
          // 跳转到登录页面
          router.push('/login')
          // 直接返回，不再抛出错误
          return Promise.reject('登录已过期')
        default:
          Message({
            message: error.response.data.message || '系统错误',
            type: 'error',
            duration: 2000
          })
      }
    } else {
      Message({
        message: '网络错误，请稍后重试',
        type: 'error',
        duration: 2000
      })
    }
    return Promise.reject(error)
  }
)

export default service 